package com.imooc.business.processor.processor;


import com.imooc.business.util.report.vo.ReportItem;
import com.imooc.module.collect.enums.PeriodEnum;
import com.imooc.module.reponse.QueryDateMetaResponse;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Tim
 * @description: 协作类，策略模式
 */
public abstract class QueryMetaDataProcessor implements QueryDateProcessor<QueryDateMetaResponse.DateView>, ApplicationContextAware, SmartInitializingSingleton {

    private static ApplicationContext applicationContext;
    private static final Map<Integer, QueryMetaDataProcessor> processorMap = new HashMap<>();

    /**
     * 
     * @param dateViews
     * @param periodType
     */
    public void queryProcessor(List<QueryDateMetaResponse.DateView> dateViews, Integer periodType){
        QueryMetaDataProcessor queryMetaDataProcessor = processorMap.get(periodType);
        if (queryMetaDataProcessor != null){
            queryMetaDataProcessor.process(dateViews);
        } else {
            processorMap.values().stream().forEach((processor)->processor.process(dateViews));
        }
    }


    public void buildDateViews(List<ReportItem> reportItems, List<QueryDateMetaResponse.DateView> resList) {
        List<QueryDateMetaResponse.DateView> dateViewList = reportItems.parallelStream().map(item -> new QueryDateMetaResponse.DateView(item.getName(), item.getFullName(),
                item.getClickAble(), new QueryDateMetaResponse.Params(item.getParams().getStartDate(), item.getParams().getEndDate(), item.getParams().getTimeType()))).collect(Collectors.toList());
        resList.addAll(dateViewList);
    }


    /**
     * 所有bean初始化完成之后，然后初始化processorMap
     */
    @Override
    public void afterSingletonsInstantiated(){
        processorMap.put(PeriodEnum.DAY.getType(), applicationContext.getBean(QueryDayMetaDataProcessor.class));
        processorMap.put(PeriodEnum.WEEK.getType(), applicationContext.getBean(QueryWeekMetaDataProcessor.class));
        processorMap.put(PeriodEnum.MONTH.getType(), applicationContext.getBean(QueryMonthMetaDataProcessor.class));
        processorMap.put(PeriodEnum.SEMESTER.getType(), applicationContext.getBean(QuerySemesterMetaDataProcessor.class));
        processorMap.put(PeriodEnum.SCHOOL_YEAR.getType(), applicationContext.getBean(QuerySchoolYearMetaDataProcessor.class));
    }


    protected abstract void process(List<QueryDateMetaResponse.DateView> dateViews);

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
